	package kr.pe.dothome.yyar.myphone.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;
import android.util.Log;

public class C2DMDataSendingTask extends AsyncTask<String, Void, Boolean>{
	
	@Override
	protected Boolean doInBackground(String... params) {
		boolean result = true;
		
		try {
		if(params.length >= 3)
			result =  sendMessage(params);
		else
			result = false;
		}
		catch (Exception e) {
			result = false;
		}
		
		return result;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		if(result)
			Log.d("Registration", "Success");
		else
			Log.d("Registration", "Failed");
	}
	
	private boolean sendMessage(String... params) throws Exception {
		URL url = new URL(
				"http://yyar.dothome.co.kr/myphone/insert_c2dm_rid.php"); // URL

		HttpURLConnection http = (HttpURLConnection) url.openConnection();

		http.setDefaultUseCaches(false);
		http.setDoInput(true);
		http.setDoOutput(true);
		http.setRequestMethod("POST");

		http.setRequestProperty("content-type",
				"application/x-www-form-urlencoded");

		OutputStreamWriter outStream = new OutputStreamWriter(
				http.getOutputStream(), "EUC-KR");
		PrintWriter writer = new PrintWriter(outStream);
		writer.write("rid="+params[0]
				+"&did="+params[1]
				+"&phonenumber="+params[2]);
		writer.flush();

		InputStreamReader tmp = new InputStreamReader(
				http.getInputStream(), "EUC-KR");
		BufferedReader reader = new BufferedReader(tmp);
		
		StringBuilder builder = new StringBuilder();
		String str;
		while ((str = reader.readLine()) != null) {
			builder.append(str + "\n");
		}
		return !builder.toString().contains("NO");
	}
}
